<?php
/************************
 *  Codenova.pl Project
 *  Created by: Kamil Mrzygłód
 *
 *  (c) 2013 by Codenova.pl
 *  All Right Reserved
 ***********************/

namespace Gotcha\App\Extensions;

// File system class

use Gotcha\App\GotchaBootstrap;
use Gotcha\App\Repositories\GotchaXMLRepository;
use Gotcha\App\Types\Arrays;
use Gotcha\App\Types\String;

class FileSystemExtension extends GotchaBootstrap {
    // PRIVATE STATIC
    private static $configRepository; // Repository for whole configuration stored in config.xml
    private static $routesRepository; // Repository for the routes

    public static function CheckFileExistence(String $file, String $path) {
        if (file_exists($path.$file)) {
            return true;
        }
        return false;
    }

    public static function CheckDirExistence(String $dir) {
        if (is_dir($dir)) {
            return true;
        }
        return false;
    }

    public function saveConfigToRepository() {
        // Check for existence builded config repository
        if(empty(self::$configRepository)) {
            $config = new Arrays(array());
            $xml = simplexml_load_file(GOTCHA_ROOT_DIR.'\App\Config\config.xml');

            // Push config values and names to an array
            foreach ($xml->property as $property) {
                // In order to get easy access to property names,
                // we have to typecast SimpleXML object into
                // array
                $typecastedSimpleXmlObject = (array)$property->attributes();

                // Push property name and value using typecasted SimpleXML
                // object and its @attributes key
                $config->array[key($typecastedSimpleXmlObject['@attributes'])] = (string)$typecastedSimpleXmlObject['@attributes'][key($typecastedSimpleXmlObject['@attributes'])];
            }

            // We put builded array to a repository for
            // easier access and saving some resources
            $configRepository = new GotchaXMLRepository();
            $configRepository->config = $config;
            self::$configRepository = $configRepository->config;
        }
    }

    public static function xmlFileHandler(String $file, String $key) {
        // Return handler xml file
        if (parent::$fatalError === false) {
            // [BUGFIX] - Not checking file existence causes
            // fatal error called each time handler is
            // called with wrong filename
            if (self::CheckFileExistence($file, new String(GOTCHA_ROOT_DIR)) === false) {
                ErrorsExtension::throwErrorAndSaveLog(new String('REQUIRED_XML_FILE_DOESNT_EXISTS'), new Arrays(array(new String(GOTCHA_ROOT_DIR.$file))));
            }

            $config = new Arrays(array());
            $xml = simplexml_load_file(GOTCHA_ROOT_DIR.'\App\Config\config.xml');

            // Push config values and names to an array
            foreach ($xml->property as $property) {
                // In order to get easy access to property names,
                // we have to typecast SimpleXML object into
                // array
                $typecastedSimpleXmlObject = (array)$property->attributes();

                // Push property name and value using typecasted SimpleXML
                // object and its @attributes key
                $config->array[key($typecastedSimpleXmlObject['@attributes'])] = (string)$typecastedSimpleXmlObject['@attributes'][key($typecastedSimpleXmlObject['@attributes'])];
            }

            // Make sure key exists
            if (array_key_exists((string)$key, $config->array)) {
                // Return only pointed key
                return $config->array[(string)$key];
            } else {
                // New log entry
                ErrorsExtension::throwErrorAndSaveLogWithoutCulture(new String('REQUIRED_XML_KEY_DOESNT_EXISTS'), new Arrays(array($key)));
            }
        }

        return null;
    }

    protected function processRoutesFile(String $file) {
        // Local variables
        $routes = array();
		
		if (self::CheckFileExistence($file, new String(GOTCHA_ROOT_DIR)) === false) {
			ErrorsExtension::throwErrorAndSaveLog(new String('REQUIRED_XML_FILE_DOESNT_EXISTS'), new Arrays(array(new String(GOTCHA_ROOT_DIR.$file))));
			exit;
		}

        $xml = simplexml_load_file(GOTCHA_ROOT_DIR.$file);

        // Typecast whole file into array and
        // search for current request
        foreach ($xml->route as $route) {
            // Push URLs into array
            $routes[(string)$route->attributes()->url] = array('module' => (string)$route->attributes()->module, 'controller' => (string)$route->attributes()->controller, 'action' => (string)$route->attributes()->action);
        }

        // Save current routes
        $routesRepository = new GotchaXMLRepository();
        $routesRepository->routes = $routes;
        self::$routesRepository = $routesRepository->routes;
    }
	
	protected static function processCultureFile(String $key, String $file) {
        // Local variables
        $registry = array();
		
		if (self::CheckFileExistence($file, new String(GOTCHA_ROOT_DIR)) === false) {
			ErrorsExtension::throwErrorAndSaveLog(new string('REQUIRED_XML_FILE_DOESNT_EXISTS'), new Arrays(array(new String(GOTCHA_ROOT_DIR.$file))));
			exit;
		}

        $xml = simplexml_load_file(GOTCHA_ROOT_DIR.$file);

        // Typecast whole file into array and
        // search for current request
        foreach ($xml->registry as $register) {
            // Push URLs into array
            $registry[(string)$register->attributes()->id] = (string)$register->attributes()->text;
        }

        // Make sure key exists
		if (array_key_exists((string)$key, $registry)) {
			// Return only pointed key
			return $registry[(string)$key];
		} else {
			// New log entry
			ErrorsExtension::throwErrorAndSaveLog(new String('REQUIRED_XML_KEY_DOESNT_EXISTS'), new Arrays(array($key)));
			exit;
		}
    }

    private static function returnConfigRepository() {
        return self::$configRepository;
    }

    private static function returnRoutesRepository() {
        return self::$routesRepository;
    }

    public static function returnConfigValue(String $key) {
        if(empty(self::$configRepository)) {
            self::saveConfigToRepository();
        }

        $configRepository = self::returnConfigRepository();
        return $configRepository->array[$key->string];
    }

    public static function returnRoutesValues() {
        if(empty(self::$routesRepository)) {
            self::saveConfigToRepository();
        }

        $routesRepository = self::returnRoutesRepository();
        return $routesRepository;
    }
}